package com.tangcco.lockwell.controller.student;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import com.tangcco.lockwell.base.RestResponse;
import com.tangcco.lockwell.context.WebContext;
import com.tangcco.lockwell.domain.*;
import com.tangcco.lockwell.domain.dto.TextContentChildDto;
import com.tangcco.lockwell.domain.dto.TextContentDto;
import com.tangcco.lockwell.domain.dto.english.EnglishTextDto;
import com.tangcco.lockwell.domain.dto.english.QuestionEnglishInfoDto;
import com.tangcco.lockwell.domain.dto.english.ReadingContent;
import com.tangcco.lockwell.domain.dto.politics.QuestionPoliticsChildInfoDto;
import com.tangcco.lockwell.domain.dto.politics.QuestionPoliticsInfoDto;
import com.tangcco.lockwell.domain.dto.politics.QuestionPoliticsListDto;
import com.tangcco.lockwell.domain.enums.CheckTypeEnum;
import com.tangcco.lockwell.domain.enums.ExamPaperTypeEnum;
import com.tangcco.lockwell.service.*;
import com.tangcco.lockwell.utility.JsonUtil;
import com.tangcco.lockwell.utility.StudentSubjectUtil;
import com.tangcco.lockwell.viewmodel.admin.question.QuestionVm;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/student/question")
public class QuestionController {

    private static final Logger logger = Logger.getLogger(QuestionController.class);
    @Autowired
    private StudentSubjectUtil studentSubjectUtil;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private TextContentService textContentService;
    @Autowired
    private ExamPaperService examPaperService;
    @Autowired
    private AnswerSheetService answerSheetService;
    @Autowired
    private WebContext webContext;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private DataDictionaryService dataDictionaryService;
    @Autowired
    private VocabularyListService vocabularyListService;
    @Autowired
    private AnswerContentRecordService answerContentRecordService;


    /**
     * 英语历年真题列表
     * @param year
     * @param subjectName
     * @param paperType
     * @return
     */
    @RequestMapping("/getQuestionListForEnglish")
    public RestResponse<Map<String, List<TextContentDto>>> getQuestionListForEnglish(@RequestParam(name = "year",required = false) Integer year,
                                                                          @RequestParam(name = "subjectName",required = false) String subjectName,
                                                                          @RequestParam(name = "paperType",required = false) Integer paperType,
                                                                                     @RequestParam(name = "examPaperId",required = false)Integer examPaperId) {
        logger.info("getQuestionInfo: year=" + year + ", subjectName=" + subjectName + ", paperType=" + paperType );
        ExamPaper examPaper = new ExamPaper();
        if(Objects.nonNull(examPaperId)){
            //周测
            examPaper = examPaperService.getExamPaperById(examPaperId);
            if(examPaper==null){
                logger.info("未查询到相关试卷，examPaperId="+examPaper);
                return RestResponse.ok();
            }
        }else{
            //刷题
            ExamPaper ep = new ExamPaper();
            ep.setSubjectId(studentSubjectUtil.getSubjectIdByUser(subjectName));
            ep.setPaperType(paperType);
            ep.setGradeLevel(year);
            List<ExamPaper> examPaperList = examPaperService.selectList(ep);
            if(CollectionUtil.isEmpty(examPaperList)){
                logger.info("该年份没有试卷，year="+year);
                return RestResponse.ok();
            }
            examPaper = examPaperList.get(0);
        }
        TextContent textContent = textContentService.selectById(examPaper.getFrameTextContentId());
        if (textContent==null ||textContent.getContent()==null){
            logger.info("TextContent="+examPaper.getFrameTextContentId()+"不存在");
            return RestResponse.ok();
        }
        List<TextContentDto> contentList = JsonUtil.toJsonListObject(textContent.getContent(), TextContentDto.class);
        if(CollectionUtil.isEmpty(contentList)){
            logger.info("TextContent="+examPaper.getFrameTextContentId()+"不存在");
            return RestResponse.ok();
        }
        Map<String, List<TextContentDto>> contentMap = contentList.stream().filter(e ->e.getName()!=null && CollectionUtil.isNotEmpty(e.getQuestionItems()))
                .collect(Collectors.groupingBy(TextContentDto::getName));
        return RestResponse.ok(contentMap);
    }
    /**
     * 获取试题信息
     *
     * @param year        年份
     * @param subjectName 模块，英语
     * @param paperType   历年真题、模拟试卷
     * @param moduleType  完形填空、阅读理解、选择题
     * @return
     */
    @RequestMapping("/getQuestionInfoForEnglish")
    public RestResponse<QuestionEnglishInfoDto> getQuestionInfoForEnglish(@RequestParam(name = "year",required = false) Integer year,
                                                                          @RequestParam(name = "subjectName",required = false) String subjectName,
                                                                          @RequestParam(name = "paperType",required = false) Integer paperType,
                                                                          @RequestParam(name = "moduleType") String moduleType,
                                                                          @RequestParam(name = "currentQuestionIndex")Integer currentQuestionIndex,
                                                                          @RequestParam(name = "examPaperId",required = false)Integer examPaperId,
                                                                          @RequestParam(name = "isTest",required = false)Boolean isTest) {
        logger.info("getQuestionInfo: year=" + year + ", subjectName=" + subjectName + ", paperType=" + paperType );
        QuestionEnglishInfoDto result = new QuestionEnglishInfoDto();
        ExamPaper examPaper = new ExamPaper();
        if(Objects.nonNull(examPaperId)){
            //周测
            examPaper = examPaperService.getExamPaperById(examPaperId);
            if(examPaper==null){
                logger.info("未查询到相关试卷，examPaperId="+examPaper);
                return RestResponse.ok();
            }
        }else{
            //刷题
            ExamPaper ep = new ExamPaper();
            ep.setSubjectId(studentSubjectUtil.getSubjectIdByUser(subjectName));
            result.setSubjectName(dataDictionaryService.selectDataDictionaryById(studentSubjectUtil.getSubjectIdByUser(subjectName)).getCategoryName());
            ep.setPaperType(paperType);
            ep.setGradeLevel(year);
            List<ExamPaper> examPaperList = examPaperService.selectList(ep);
            if(CollectionUtil.isEmpty(examPaperList)){
                logger.info("该年份没有试卷，year="+year);
                return RestResponse.ok();
            }
            examPaper = examPaperList.get(0);
        }

        result.setExamPaperId(examPaper.getPaperId());
        TextContent textContent = textContentService.selectById(examPaper.getFrameTextContentId());
        if (textContent==null ||textContent.getContent()==null){
            logger.info("TextContent="+examPaper.getFrameTextContentId()+"不存在");
            return RestResponse.ok();
        }
        List<TextContentDto> contentList = JsonUtil.toJsonListObject(textContent.getContent(), TextContentDto.class);
        if(CollectionUtil.isEmpty(contentList)){
            logger.info("TextContent="+examPaper.getFrameTextContentId()+"不存在");
            return RestResponse.ok();
        }
        List<TextContentChildDto> childContentList = new ArrayList<>();
        contentList.stream().filter(item-> item.getName().equals(moduleType)).forEach(item->{
            if(CollectionUtil.isNotEmpty(item.getQuestionItems())){
                childContentList.addAll(item.getQuestionItems());
            }
        });
        if(CollectionUtil.isEmpty(childContentList)){
            logger.info("TextContent="+examPaper.getFrameTextContentId()+"不存在");
            return RestResponse.ok();
        }
        TextContentChildDto childContent = childContentList.get(currentQuestionIndex-1);
        QuestionVm question = questionService.selectByIds(childContent.getId());
        result.setQuestionId(question.getId());
        result.setPictureUrl(question.getPicture());
        result.setCurrentQuestionIndex(currentQuestionIndex);
        result.setSelectedYear(question.getGradeLevel());
        if(question.getTextContent() != null){
            List<QuestionPoliticsChildInfoDto> questionList = JsonUtil.toJsonListObject(question.getTextContent(), QuestionPoliticsChildInfoDto.class);
            if(CollectionUtil.isNotEmpty(questionList)){
                result.setQuestions(questionList);
            }
        }
        //查询出当前用户的生词本
        VocabularyList vocabularyList = new VocabularyList();
        vocabularyList.setUserId(webContext.getCurrentUser().getUserId());
        List<VocabularyList> vocabularyLists = vocabularyListService.selectByCondition(vocabularyList);
        Map<String,List<VocabularyList>> vocabularyMap = vocabularyLists.stream().collect(Collectors.groupingBy(VocabularyList::getNewWord));
        List<String> vocabularyListStr = vocabularyLists.stream().map(VocabularyList::getNewWord).distinct().collect(Collectors.toList());
        result.setVocabList(vocabularyListStr);
        List<ReadingContent> readingContents = new ArrayList<>();
        List<String> nalysisTextList = new ArrayList<>();
        if(question.getArticleContent()!=null && moduleType.contains("阅读理解")){
            // 使用split方法按照换行符进行分割，将每一行作为一个元素存入集合
            String[] splitLines = question.getArticleContent().split("\\n");
            for (String line : splitLines) {
                nalysisTextList.add(line);
                ReadingContent readingContent = new ReadingContent();
                List<EnglishTextDto> englishTextList = new ArrayList<>();
                wordSplitWithMatcher(line, englishTextList,vocabularyMap);
                readingContent.setEnglishText(englishTextList);
                readingContents.add(readingContent);
            }
        }
        result.setArticle(question.getArticleContent());
        result.setArticleId(question.getArticleId());
        result.setNalysisTextList(nalysisTextList);
        result.setReadingContent(readingContents);


        //TODO 需求细节逻辑是我自己的定的，后续这个复杂逻辑需要修改的话，从这里入手，查询当前用户答题记录
        Integer type = isTest==null? ExamPaperTypeEnum.EXERCISE.getCode() :isTest?ExamPaperTypeEnum.WEEKTEST.getCode():ExamPaperTypeEnum.EXERCISE.getCode();
        List<AnswerContentRecord> answerContentRecordList = answerContentRecordService.selectByExamPaperIdAndUserIdAndQuestionId(type,examPaper.getPaperId(),webContext.getCurrentUser().getUserId(),question.getId());
        result.setAnswerContentRecords(answerContentRecordList);

        return RestResponse.ok(result);
    }


    private void wordSplitWithMatcher(String content,List<EnglishTextDto> lists,Map<String,List<VocabularyList>> vocabularyMap){
        Pattern pattern = Pattern.compile("\\S+");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            EnglishTextDto englishText = new EnglishTextDto();
            String s = matcher.group();
            englishText.setWord(s);
            String ss = s.replaceAll("[\\p{Punct}]+", "");
            if(CollectionUtil.isNotEmpty(vocabularyMap) &&vocabularyMap.get(ss)!=null){
              englishText.setNewWord(true);
            }else{
              englishText.setNewWord(false);
            }
            lists.add(englishText);
        }
    }
    public static boolean isSymbol(String str) {
        // 定义符号的正则表达式，匹配常见标点符号、特殊符号等
        String symbolPattern = "[\\p{Punct}\\p{S}]+";
        return Pattern.matches(symbolPattern, str);
    }
    /**
     * 查询政治历年真题
     * @param paperType 历年真题
     * @return
     */
    @RequestMapping("/getQuestionPoliticsList")
    public RestResponse<List<QuestionPoliticsListDto>> getQuestionPoliticsList(@RequestParam(name = "paperType")Integer paperType){
        List<QuestionPoliticsListDto> result = new ArrayList<>();
        ExamPaper ep = new ExamPaper();
        ep.setSubjectId(studentSubjectUtil.getSubjectIdByUser("politics"));
        ep.setPaperType(paperType);
        List<ExamPaper> examPaperList = examPaperService.selectList(ep);
        if(CollectionUtil.isEmpty(examPaperList)){
            logger.info("政治paperType"+paperType+"没有试卷");
            return RestResponse.ok(result);
        }
        Map<Integer, List<ExamPaper>> groupExamPaper = examPaperList.stream().filter(e ->e.getGradeLevel()!=null)
                .collect(Collectors.groupingBy(ExamPaper::getGradeLevel));
        if(CollectionUtil.isNotEmpty(groupExamPaper)){
            groupExamPaper.forEach((gradeLevel,examPapers)->{
                if(CollectionUtil.isNotEmpty(examPapers)){
                    ExamPaper examPaper = examPapers.get(0);
                    QuestionPoliticsListDto dto = new QuestionPoliticsListDto();
                    dto.setGradeLevel(gradeLevel);
                    dto.setQuestionTitile(gradeLevel+"年真题");
                    dto.setExamPaperId(examPaper.getPaperId());
                    TextContent textContent = textContentService.selectById(examPaper.getFrameTextContentId());
                    List<TextContentDto> contentList = JsonUtil.toJsonListObject(textContent.getContent(), TextContentDto.class);
                    if(CollectionUtil.isEmpty(contentList)){
                        logger.info("TextContent="+examPaper.getFrameTextContentId()+"不存在");
                    }
                    List<TextContentChildDto> childContentList = new ArrayList<>();
                    contentList.forEach(item->{
                        if(CollectionUtil.isNotEmpty(item.getQuestionItems())){
                            childContentList.addAll(item.getQuestionItems());
                        }
                    });
                    dto.setQuestionTotalNum(childContentList.size());
                    AnswerSheet answerSheet = new AnswerSheet();
                    answerSheet.setPaperId(examPaper.getPaperId());
                    answerSheet.setUserId(webContext.getCurrentUser().getUserId());
                    List<AnswerSheet> answerSheetList = answerSheetService.selectList(answerSheet);
                    if(CollectionUtil.isNotEmpty(answerSheetList)){
                        AnswerSheet aw = answerSheetList.get(0);
                        if(aw.getNumberQuestionsCompleted()!=null && examPaper.getQuestionCount()!=null){
                            // 计算完成率
                            dto.setCompleteRate(NumberUtil.div(aw.getNumberQuestionsCompleted(), examPaper.getQuestionCount())
                                    .multiply(new BigDecimal(  100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                        if(aw.getNumberCorrectAnswers()!=null && examPaper.getQuestionCount()!=null){
                            // 计算正确率
                            dto.setAccuracyRate(NumberUtil.div(aw.getNumberCorrectAnswers(), examPaper.getQuestionCount())
                                    .multiply(new BigDecimal(  100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                        dto.setNumberQuestionsCompleted(aw.getNumberQuestionsCompleted());
                        dto.setNumberCorrectAnswers(aw.getNumberCorrectAnswers());
                        dto.setNumberIncorrectQuestions(aw.getNumberIncorrectQuestions());
                        dto.setRemainingQuestions(aw.getRemainingQuestions());
                    }
                    result.add(dto);
                }
            });
        }
        //按年份排序，大年份在上面
        result.sort((o1, o2) -> o2.getGradeLevel().compareTo(o1.getGradeLevel()));
        return RestResponse.ok(result);
    }
    /**
     * 查询政治专项练习
     * @param paperType 专项练习
     * @return
     */
    @RequestMapping("/getQuestionSpecialPoliticsList")
    public RestResponse<List<QuestionPoliticsListDto>> getQuestionSpecialPoliticsList(@RequestParam(name = "paperType")Integer paperType){
        List<QuestionPoliticsListDto> result = new ArrayList<>();
        ExamPaper ep = new ExamPaper();
        ep.setSubjectParentId(studentSubjectUtil.getSubjectIdByUser("politics"));
        ep.setPaperType(paperType);
        List<ExamPaper> examPaperList = examPaperService.selectList(ep);
        if(CollectionUtil.isEmpty(examPaperList)){
            logger.info("政治paperType"+paperType+"没有试卷");
            return RestResponse.ok(result);
        }
        Map<Integer, List<ExamPaper>> groupExamPaper = examPaperList.stream().filter(e ->e.getSubjectId()!=null)
                .collect(Collectors.groupingBy(ExamPaper::getSubjectId));
        if(CollectionUtil.isNotEmpty(groupExamPaper)){
            groupExamPaper.forEach((subjectId,examPapers)->{
                if(CollectionUtil.isNotEmpty(examPapers)){
                    ExamPaper examPaper = examPapers.get(0);
                    QuestionPoliticsListDto dto = new QuestionPoliticsListDto();
                    DataDictionary dataDictionary = dataDictionaryService.selectById(subjectId);
                    dto.setQuestionTitile(dataDictionary!=null? dataDictionary.getCategoryName():"");
                    dto.setExamPaperId(examPaper.getPaperId());
                    TextContent textContent = textContentService.selectById(examPaper.getFrameTextContentId());
                    List<TextContentDto> contentList = JsonUtil.toJsonListObject(textContent.getContent(), TextContentDto.class);
                    if(CollectionUtil.isEmpty(contentList)){
                        logger.info("TextContent="+examPaper.getFrameTextContentId()+"不存在");
                    }
                    List<TextContentChildDto> childContentList = new ArrayList<>();
                    contentList.forEach(item->{
                        if(CollectionUtil.isNotEmpty(item.getQuestionItems())){
                            childContentList.addAll(item.getQuestionItems());
                        }
                    });
                    dto.setQuestionTotalNum(childContentList.size());
                    AnswerSheet answerSheet = new AnswerSheet();
                    answerSheet.setPaperId(examPaper.getPaperId());
                    answerSheet.setUserId(webContext.getCurrentUser().getUserId());
                    List<AnswerSheet> answerSheetList = answerSheetService.selectList(answerSheet);
                    if(CollectionUtil.isNotEmpty(answerSheetList)){
                        AnswerSheet aw = answerSheetList.get(0);
                        if(aw.getNumberQuestionsCompleted()!=null && dto.getQuestionTotalNum()!=0){
                            // 计算完成率
                            dto.setCompleteRate(NumberUtil.div(aw.getNumberQuestionsCompleted(), dto.getQuestionTotalNum())
                                    .multiply(new BigDecimal(  100)).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
//                        if(aw.getNumberCorrectAnswers()!=null && examPaper.getQuestionCount()!=null){
//                            // 计算正确率
//                            dto.setAccuracyRate(NumberUtil.div(aw.getNumberCorrectAnswers(), examPaper.getQuestionCount())
//                                    .multiply(new BigDecimal(  100)).setScale(2, BigDecimal.ROUND_HALF_UP));
//                        }
                        dto.setNumberQuestionsCompleted(aw.getNumberQuestionsCompleted());
                        dto.setNumberCorrectAnswers(aw.getNumberCorrectAnswers());
                        dto.setNumberIncorrectQuestions(aw.getNumberIncorrectQuestions());
                        dto.setRemainingQuestions(aw.getRemainingQuestions());
                    }
                    result.add(dto);
                }
            });
        }
        return RestResponse.ok(result);
    }


    /**
     * 查询正式历史真题详情
     * @param examPaperId 题目id
     * @return
     */
    @RequestMapping("/getQuestionPoliticsInfo")
    public RestResponse<QuestionPoliticsInfoDto> getQuestionPoliticsInfo(@RequestParam(name = "examPaperId")Integer examPaperId,
                                                                         @RequestParam(name = "currentQuestionIndex")Integer currentQuestionIndex,
                                                                         @RequestParam(name = "isTest",required = false)Boolean isTest) {
        QuestionPoliticsInfoDto result = new QuestionPoliticsInfoDto();
        // 政治题目详情
        ExamPaper examPaper = examPaperService.selectById(examPaperId);
        if(examPaper==null || examPaper.getFrameTextContentId()==null){
            logger.info("examPaperId="+examPaperId+"不存在");
            return RestResponse.ok();
        }
        TextContent textContent = textContentService.selectById(examPaper.getFrameTextContentId());
        if (textContent==null ||textContent.getContent()==null){
            logger.info("TextContent="+examPaper.getFrameTextContentId()+"不存在");
            return RestResponse.ok();
        }
        List<TextContentDto> contentList = JsonUtil.toJsonListObject(textContent.getContent(), TextContentDto.class);
        if(CollectionUtil.isEmpty(contentList)){
            logger.info("TextContent="+examPaper.getFrameTextContentId()+"不存在");
            return RestResponse.ok();
        }
        List<TextContentChildDto> childContentList = new ArrayList<>();
        contentList.forEach(item->{
            if(CollectionUtil.isNotEmpty(item.getQuestionItems())){
                childContentList.addAll(item.getQuestionItems());
            }
        });
        DataDictionary dataDictionary = dataDictionaryService.selectById(examPaper.getSubjectId());
        if(dataDictionary!=null){
            result.setTitle(dataDictionary.getCategoryName());
        }
        TextContentChildDto childContent = childContentList.get(currentQuestionIndex-1);
        QuestionVm question = questionService.selectByIds(childContent.getId());
        result.setQuestionId(question.getId());
        result.setTotalQuestions(childContentList.size());
        result.setCurrentQuestionIndex(currentQuestionIndex);
        result.setSelectedYear(question.getGradeLevel());
        if(StringUtils.isEmpty(question.getCorrect())){
            result.setCheckType(CheckTypeEnum.TICH_TEXT.getCode());
            if(question.getArticleContent()!=null){
                result.setArticle(question.getArticleContent());
            }
        }else if(question.getCorrect().split(",").length==1){
            result.setCheckType(CheckTypeEnum.SINGLE_CHECK.getCode());
        }else if(question.getCorrect().split(",").length>1){
            result.setCheckType(CheckTypeEnum.MULTI_CHECK.getCode());
        }
        StringBuilder sb = new StringBuilder();
        if(question.getSubjectName()!=null){
            sb.append(question.getSubjectName());
        }
        if(question.getChapterName()!=null){
            sb.append("-").append(question.getChapterName());
        }
        result.setChapter(sb.toString());
        if(question.getTextContent() != null){
            List<QuestionPoliticsChildInfoDto> questionList = JsonUtil.toJsonListObject(question.getTextContent(), QuestionPoliticsChildInfoDto.class);
            if(CollectionUtil.isNotEmpty(questionList)){
                result.setChildInfo(questionList);
            }
        }
        //TODO 需求细节逻辑是我自己的定的，后续这个复杂逻辑需要修改的话，从这里入手，查询当前用户答题记录
        Integer type = isTest==null? ExamPaperTypeEnum.EXERCISE.getCode() :isTest?ExamPaperTypeEnum.WEEKTEST.getCode():ExamPaperTypeEnum.EXERCISE.getCode();
        List<AnswerContentRecord> answerContentRecordList = answerContentRecordService.selectByExamPaperIdAndUserId(type,examPaperId,webContext.getCurrentUser().getUserId());
        result.setAnswerContentRecords(answerContentRecordList);
        return RestResponse.ok(result);
    }

    /**
     * 查询正式历史真题详情,按题目id查询
     * @param questionId 题目id
     * @return
     */
    @RequestMapping("/getQuestionPoliticsInfoById")
    public RestResponse<QuestionPoliticsInfoDto> getQuestionPoliticsInfoById(@RequestParam(name = "questionId")Integer questionId) {
        if(questionId==null){
            return RestResponse.ok();
        }
        QuestionPoliticsInfoDto result = new QuestionPoliticsInfoDto();
        QuestionVm question = questionService.selectByIds(questionId);
        result.setQuestionId(question.getId());
        result.setCorrectAnswer(question.getCorrect());
        result.setSelectedYear(question.getGradeLevel());
        if(StringUtils.isEmpty(question.getCorrect())){
            result.setCheckType(CheckTypeEnum.TICH_TEXT.getCode());
            if(question.getArticleContent()!=null){
                result.setArticle(question.getArticleContent());
            }
        }else if(question.getCorrect().split(",").length==1){
            result.setCheckType(CheckTypeEnum.SINGLE_CHECK.getCode());
        }else if(question.getCorrect().split(",").length>1){
            result.setCheckType(CheckTypeEnum.MULTI_CHECK.getCode());
        }
        StringBuilder sb = new StringBuilder();
        if(question.getSubjectName()!=null){
            sb.append(question.getSubjectName());
        }
        if(question.getChapterName()!=null){
            sb.append("-").append(question.getChapterName());
        }
        result.setChapter(sb.toString());
        if(question.getTextContent() != null){
            List<QuestionPoliticsChildInfoDto> questionList = JsonUtil.toJsonListObject(question.getTextContent(), QuestionPoliticsChildInfoDto.class);
            if(CollectionUtil.isNotEmpty(questionList)){
                result.setChildInfo(questionList);
            }
        }
        return RestResponse.ok(result);
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String c = "    A group of labour MPs, among them Yvette Cooper, are bringing in the new year with a call to institute a UK “town of culture” award. The proposal is that it should sit alongside the existing city of culture title, which was held by Hull in 2017, and has been awarded to Coventry for 2021. Cooper and her colleagues argue that the success of the crown for Hull, where it brought in £220m of investment and an avalanche of arts, ought not to be confined to cities. Britain’s towns, it is true, are not prevented from applying, but they generally lack the resources to put together a bid to beat their bigger competitors. A town of culture award could, it is argued, become an annual event, attracting funding and creating jobs.\n" +
                "    Some might see the proposal as a booby prize for the fact that Britain is no longer able to apply for the much more prestigious title of European capital of culture, a sought-after award bagged by Glasgow in 1990 and Liverpool in 2008. A cynic might speculate that the UK is on the verge of disappearing into an endless fever of self-celebration in its desperation to reinvent itself for the post-Brexit world: after town of culture, who knows what will follow—village of culture? Suburb of culture? Hamlet of culture\n" +
                "    It is also wise to recall that such titles are not a cure-all. A badly run “year of culture” washes in and out of a place like the tide, bringing prominence for a spell but leaving no lasting benefits to the community. The really successful holders of such titles are those that do a great deal more than fill hotel bedrooms and bring in high-profile arts events and good press for a year. They transform the aspirations of the people who live there; they nudge the self-image of the city into a bolder and more optimistic light. It is hard to get right, and requires a remarkable degree of vision, as well as cooperation between city authorities, the private sector, community groups and cultural organisations. But it can be done: Glasgow’s year as European capital of culture can certainly be seen as one of a complex series of factors that have turned the city into the powerhouse of art, music and theatre that it remains today.\n" +
                "    A “town of culture” could be not just about the arts but about honouring a town’s peculiarities—helping sustain its high street, supporting local facilities and above all celebrating its people. Jeremy Wright, the culture secretary, should welcome this positive, hope-filled proposal, and turn it into action.\n";
//        System.out.println(c);


        String[] splitLines =c.split("\\n");
        for (String line : splitLines) {
            System.out.println(line);
        }
    }

//    public static void main(String[] args) {
//        String json = "[{\n" +
//                "\t\"qtitle\": \"习近平总书记在为《复兴文库》所写的序言中指出：“修史立典，存史启智，以文化人，这是中华民族延续几千年的一个传统”。“编纂出版《复兴文库》大型历史文献丛书，就是要通过对近代以来重要思想文献的选编，述录先人的开拓，启迪来者的奋斗。”“历史是最好的教科书，一切向前走，都不能忘记走过的路；走得再远、走到再光辉的未来，也不能忘记走过的过去。”这表明\",\n" +
//                "\t\"item\": [{\n" +
//                "\t\t\"prefix\": \"A\",\n" +
//                "\t\t\"content\": \"历史、现实、未来是相通的\"\n" +
//                "\t},\n" +
//                "\t{\n" +
//                "\t\t\"prefix\": \"B\",\n" +
//                "\t\t\"content\": \"一切历史都是当代史\"\n" +
//                "\t},\n" +
//                "\t{\n" +
//                "\t\t\"prefix\": \"C\",\n" +
//                "\t\t\"content\": \"历史过程不包含任何偶然的因素\"\n" +
//                "\t},\n" +
//                "\t{\n" +
//                "\t\t\"prefix\": \"D\",\n" +
//                "\t\t\"content\": \"历史事件往往可以完整重复和再现\"\n" +
//                "\t}]\n" +
//                "}]";
//        List<QuestionPoliticsChildInfoDto> questionList = JsonUtil.toJsonListObject(json, QuestionPoliticsChildInfoDto.class);
//        for (QuestionPoliticsChildInfoDto question : questionList) {
//            System.out.println("题目：" + question.getItem());
//            List<Option> options = question.getItem();
//            for (Option s : options) {
//                System.out.println(s.getPrefix() + ":" + s.getContent());
////                System.out.println("选项 " + option.getOptionCode() + "：" + option.getOptionText());
//            }
//            //        JSONObject obj = JSONUtil.parseObj(json);
//        }
//        System.out.println(2222);
//
//    }
}
